<!--
使用antd原生Form生成 详细用法参考ant-design-vue Form组件文档
vscode默认配置文件会自动格式化/移除未使用依赖
-->
<script setup lang="ts">
import type { RuleObject } from 'ant-design-vue/es/form';

import type { JobLogForm } from '#/api/system/jobLog/model';

import { computed, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { cloneDeep } from '@vben/utils';

import { Form, FormItem, Input, RadioGroup, Textarea } from 'ant-design-vue';
import { pick } from 'lodash-es';

import { jobLogAdd, jobLogInfo, jobLogUpdate } from '#/api/system/jobLog';

const emit = defineEmits<{ reload: [] }>();

const isUpdate = ref(false);
const title = computed(() => {
  return isUpdate.value ? $t('pages.common.edit') : $t('pages.common.add');
});

/**
 * 定义默认值 用于reset
 */
const defaultValues: Partial<JobLogForm> = {
  jobLogId: undefined,
  jobName: undefined,
  jobGroup: undefined,
  invokeTarget: undefined,
  jobMessage: undefined,
  status: undefined,
  exceptionInfo: undefined,
};

/**
 * 表单数据ref
 */
const formData = ref(defaultValues);

type AntdFormRules<T> = Partial<Record<keyof T, RuleObject[]>> & {
  [key: string]: RuleObject[];
};
/**
 * 表单校验规则
 */
const formRules = ref<AntdFormRules<JobLogForm>>({
  jobName: [{ required: true, message: '任务名称不能为空' }],
  jobGroup: [{ required: true, message: '任务组名不能为空' }],
  invokeTarget: [{ required: true, message: '调用目标字符串不能为空' }],
  jobMessage: [{ required: true, message: '日志信息不能为空' }],
  status: [{ required: true, message: '执行状态不能为空' }],
  exceptionInfo: [{ required: true, message: '异常信息不能为空' }],
});

/**
 * useForm解构出表单方法
 */
const { validate, validateInfos, resetFields } = Form.useForm(
  formData,
  formRules,
);

const [BasicModal, modalApi] = useVbenModal({
  class: 'w-[550px]',
  fullscreenButton: false,
  closeOnClickModal: false,
  onClosed: handleCancel,
  onConfirm: handleConfirm,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    modalApi.modalLoading(true);

    const { id } = modalApi.getData() as { id?: number | string };
    isUpdate.value = !!id;

    if (isUpdate.value && id) {
      const record = await jobLogInfo(id);
      // 只赋值存在的字段
      const filterRecord = pick(record, Object.keys(defaultValues));
      formData.value = filterRecord;
    }

    modalApi.modalLoading(false);
  },
});

async function handleConfirm() {
  try {
    modalApi.modalLoading(true);
    await validate();
    // 可能会做数据处理 使用cloneDeep深拷贝
    const data = cloneDeep(formData.value);
    await (isUpdate.value ? jobLogUpdate(data) : jobLogAdd(data));
    emit('reload');
    await handleCancel();
  } catch (error) {
    console.error(error);
  } finally {
    modalApi.modalLoading(false);
  }
}

async function handleCancel() {
  modalApi.close();
  formData.value = defaultValues;
  resetFields();
}
</script>

<template>
  <BasicModal :title="title">
    <Form :label-col="{ span: 4 }">
      <FormItem label="任务名称" v-bind="validateInfos.jobName">
        <Input
          v-model:value="formData.jobName"
          :placeholder="$t('ui.formRules.required')"
        />
      </FormItem>
      <FormItem label="任务组名" v-bind="validateInfos.jobGroup">
        <Input
          v-model:value="formData.jobGroup"
          :placeholder="$t('ui.formRules.required')"
        />
      </FormItem>
      <FormItem label="调用目标字符串" v-bind="validateInfos.invokeTarget">
        <Textarea
          v-model:value="formData.invokeTarget"
          :placeholder="$t('ui.formRules.required')"
          :rows="4"
        />
      </FormItem>
      <FormItem label="日志信息" v-bind="validateInfos.jobMessage">
        <Textarea
          v-model:value="formData.jobMessage"
          :placeholder="$t('ui.formRules.required')"
          :rows="4"
        />
      </FormItem>
      <FormItem label="执行状态" v-bind="validateInfos.status">
        <RadioGroup
          option-type="button"
          button-style="solid"
          v-model:value="formData.status"
          :options="[]"
        />
      </FormItem>
      <FormItem label="异常信息" v-bind="validateInfos.exceptionInfo">
        <Textarea
          v-model:value="formData.exceptionInfo"
          :placeholder="$t('ui.formRules.required')"
          :rows="4"
        />
      </FormItem>
    </Form>
  </BasicModal>
</template>
